# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2021-08-26 16:56:22
LastEditors: peng2.zhang
LastEditTime: 2021-12-09 18:09:07
'''
import os
import requests
import xml.etree.ElementTree as ET
from ci_conclude.const import CODE
from ci_conclude.base import BaseConclude


class JunitConclude(BaseConclude):
    def get_url(self):
        return self.junit_result_url

    def get_result(self, junit_xml_path):
        if junit_xml_path.startswith("http"):
            res = requests.get(junit_xml_path)
            if res.status_code == 200 and res.ok:
                tree = ET.fromstring(res.text)
            else:
                return {}
        else:
            if os.path.exists(junit_xml_path):
                tree = ET.parse(junit_xml_path)
            else:
                return {}
        if hasattr(tree, "getroot"):
            root = tree.getroot()
            if root.tag == 'testsuite':
                testsuite = root
            else:
                testsuite = root.find("testsuite")
        else:
            if tree.tag == 'testsuite':
                testsuite = tree
            else:
                testsuite = tree.find("testsuite")

        failures = int(testsuite.attrib.get('failures', 0))
        tests = int(testsuite.attrib.get('tests', 0))
        skipped = int(testsuite.attrib.get('skipped', 0))

        # print("failures: %s" % failures)
        # print("tests: %s" % tests)
        # print("skipped: %s" % skipped)
        pass_rate = round((tests - failures - skipped) / tests, 2)
        data = {
            "failures": failures,
            "tests": tests,
            "skipped": skipped,
        }
        if int(failures) == 0:
            result = dict(code=CODE.PASS.ID, message=CODE.PASS.NAME)
        else:
            result = dict(code=CODE.FAIL.ID, message=CODE.FAIL.NAME)
        result.update(dict(data=data, prefix="junit"))
        return result
    
    def format_to_weixin(self, result_kwargs, url):
        """
            result_kwargs: {'code': -1, 'message': 'FAIL', 
                    'data': {
                            "failures": failures,
                            "tests": tests,
                            "skipped": skipped,
                            }}
            url: https://ci.ecarx.com.cn/view/stdci/job/stdci_std-data-collect-service-app-meta/11/testReport/
        """
        # title = f"#【{self.project_name}】pipeline #{self.buildid} [stage: {self.stage_name}] 统计结果"
        if result_kwargs:
            content = (f"""\n ## [单元测试结果] [{result_kwargs["message"]}] [报告地址]({url}) """
                    f"""\n > [用例总数]: <font color="comment">{result_kwargs["data"]["tests"]}</font> """
                    f"""\n > [用例跳过]: <font color="comment">{result_kwargs["data"]["skipped"]}</font> """
                    f"""\n > [用例失败]: <font color="{'comment' if result_kwargs["data"]["failures"] == 0 else 'warning'}">{result_kwargs["data"]["failures"]}</font> """)
        else:
            content = f"""\n ## [单元测试结果] \n <font color="warning">暂无数据</font>"""
        return content
